<?php
/**
 * 省市区模型
 */

namespace app\admin\model;


use app\admin\model\Region as RegionModel;
use app\common\model\BaseModel;
use custom\Err;
use PDOStatement;
use think\Collection;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class Region extends BaseModel {

    /**
     * city_code查询
     * @param $city_code
     * @return mixed
     */
    public static function cityCodeTodata($city_codes) {
        foreach ($city_codes as $k => $v) {
            if (!$v)
                unset($city_codes[$k]);
        }
        $city_codes = array_merge($city_codes);
        foreach ($city_codes as $k1 => $v1) {
            $data[] = self::getOne([['city_code', '=', $v1]], 'name')['name'];
        }
        return $data;
    }

    /**
     * 筛选多条
     * @param $map
     * @param $column
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getDatas($map, $column) {
        return db('region')
            ->where($map)
            ->field($column)
            ->select();
    }

    /**
     * 筛选单条
     * @param $map
     * @param $column
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getOne($map, $column) {
        return db('region')
            ->where($map)
            ->field($column)
            ->find();
    }

    /**
     * 获取市或者区
     * @param $params
     * @param $col
     * @return array|PDOStatement|string|Collection
     */
    public static function getCityOrArea($params, $col) {
        $House = House::getOne([['id', '=', $params['id']]], 'city_codes');
        $city_codes = $House['city_codes'];
        if (!empty($city_codes)) {
            $city_codes = explode(',', $city_codes);
            return self::getDatas([['p_code', '=', $city_codes[$col]]], 'name,city_code,rank');
        }
    }

    /**
     * 省市区联动
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getLinkage($params) {
        $rank = self::getDatas([['city_code', '=', $params['city_code']]], 'rank,city_code');
        if ($rank[0]['rank'] == 3) {
            //获取商圈
            $rank4 = BusinessArea::getDatas([['city_id', '=', $rank[0]['city_code']]], 'id,name');
            foreach ($rank4 as $k => $v) {
                $rank4[$k]['rank'] = 4;
            }
            //获取小区
            $rank5 = HouseVillage::getDatas([['city_code', '=', $rank[0]['city_code']]], 'id,name');
            foreach ($rank5 as $k => $v) {
                $rank5[$k]['rank'] = 5;
            }
            $data = compact('rank4', 'rank5');
        } else {
            //获取市或者区
            $data = self::getDatas([['p_code', '=', $params['city_code']]], 'name,city_code,rank');
        }
        return $data;
    }

    /**
     * 首页定位省市结构
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function indexCity() {
        $map[] = ['rank', 'in', '1,2'];//省市
        $map[] = ['id', 'not in', [25179, 25183]];
        $column = ['name', 'city_code', 'id', 'pid', 'initials', 'x(location) as lng', 'Y(location) as lat'];
        $data = db('region')
            ->where($map)
            ->field($column)
            ->order(['rank' => 'desc', 'initials' => 'asc'])
            ->select();
        return self::treeFilter($data);
    }

    /**
     * 获取树
     * @param $data
     * @return array
     */
    public static function treeFilter($data) {
        $data = array_column($data, null, 'id');
        $tree = [];
        foreach ($data as &$val) {
            if (isset($data[$val['pid']])) {//市
                $data[$val['pid']]['children'][] = [
                    'value'    => $val['city_code'],
                    'label'    => $val['name'],
                    'children' => $val['children'] ?? [],
                    'lat'      => empty($val['lat']) ? '' : (string)$val['lat'],
                    'lng'      => empty($val['lng']) ? '' : (string)$val['lng'],
                ];
            } else {//省
                $arr = [
                    'value'    => $val['city_code'],
                    'label'    => $val['name'],
                    'children' => $val['children'] ?? [],
                ];
                $tree[$val['initials']]['label'] = $val['initials'];
                $tree[$val['initials']]['children'][] = $arr;
            }
        }
        return array_values($tree);
    }

    /**
     * 省
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function province() {
        $map[] = ['rank', '=', 1];//省
        $map[] = ['id', 'not in', [25179, 25183]];
        $data = db('region')
            ->where($map)
            ->field('id,name')
            ->order('initials', 'asc')
            ->select();
        return $data;
    }

    /**
     * 根据省id找下面的市
     * @param $id
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getCity($id) {
        $data = db('region')
            ->where('pid', $id)
            ->field('name,city_code,x(location) as lng,Y(location) as lat')
            ->order('initials', 'asc')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['lng'] = empty($v['lng']) ? '' : (string)$v['lng'];
            $data[$k]['lat'] = empty($v['lat']) ? '' : (string)$v['lat'];
        }
        return $data;
    }

    /**
     * 根据名称查找城市
     * @param $name
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getCityname($name) {
        $data = db('region')
            ->where('name', 'like', '%' . $name . '%')
            ->where('rank', 2)
            ->field('name,city_code,x(location) as lng,Y(location) as lat')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['lng'] = empty($v['lng']) ? '' : (string)($v['lng']);
            $data[$k]['lat'] = empty($v['lat']) ? '' : (string)($v['lat']);
        }
        if (empty($data)) {
            Err::add('数据不存在');
            return false;
        }
        return $data;
    }

    /**
     * 市区商圈联动
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function cityAreabusiness($params) {
        //区域
        $areaList = db::name('region')
            ->where('p_code', 'in', $params)
            ->field(['name', 'city_code', 'pid'])
            ->select();
        $areaCode = array_column($areaList, 'city_code');
        $areaList = array_column($areaList, null, 'city_code');
        //区域下面所有商圈
        $business_area = db::name('business_area')
            ->where('city_id', 'in', $areaCode)
            ->field('name,city_id as city_code,id')
            ->select();
        foreach ($business_area as $val) {
            if (isset($areaList[$val['city_code']])) {
                $areaList[$val['city_code']]['children'][] = $val;
            }
        }
        $areaBusinessList = array_values($areaList);
        $cityList = db::name('region')
            ->where('city_code', 'in', $params)
            ->field(['name', 'city_code', 'id'])
            ->select();
        $cityList = array_column($cityList, null, 'id');
        foreach ($areaBusinessList as $val1) {
            if (isset($cityList[$val1['pid']])) {
                $cityList[$val1['pid']]['children'][] = $val1;
            }
        }
        return array_values($cityList);
    }

    /**
     * 区商圈
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function areabusiness($params) {
        //区域
        $areaList = db::name('region')
            ->where('p_code', $params['city_code'])
            ->field(['name', 'city_code', 'pid'])
            ->order('weights asc')
            ->select();
        $areaCode = array_column($areaList, 'city_code');
        $areaList = array_column($areaList, null, 'city_code');
        //区域下面所有商圈
        $business_area = db::name('business_area')
            ->where('city_id', 'in', $areaCode)
            ->field('name,city_id as city_code,id')
            ->select();
        foreach ($business_area as $val) {
            if (isset($areaList[$val['city_code']])) {
                $areaList[$val['city_code']]['children'][] = $val;
            }
        }
        return array_values($areaList);
    }

    /**
     * 修改排序
     * @param $params
     * @throws \Exception
     */
    public static function editSort($params) {
        $ids = explode(',', $params['ids']);
        if ($ids) {
            $count = count($ids);
            $int = 1;
            for ($i = 0; $i < $count; $i++) {
                $arr = [
                    'id'      => $ids[$i],
                    'weights' => $int
                ];
                $list[] = $arr;
                $int++;
            }
            $region = new self();
            $region->saveAll($list);
        }
    }

    /**
     * 所有成功
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function cityList() {
        $cityList = config('global.house_city_all');
        $data = db('region')
            ->where('city_code', 'in', $cityList)
            ->field('city_code,name')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['key'] = $v['city_code'];
            $data[$k]['val'] = $v['name'];
            unset($data[$k]['city_code']);
            unset($data[$k]['name']);
        }
        return $data;
    }


    /**
     * 可操作的城市
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function myCityList($params) {
        $city_codes = self::myCityCodes($params);
        //角色对应的城市
        $data = db('region')
            ->where('city_code', 'in', $city_codes)
            ->field('city_code,name')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['key'] = $v['city_code'];
            $data[$k]['val'] = $v['name'];
            unset($data[$k]['city_code']);
            unset($data[$k]['name']);
        }
        return $data;
    }

    /**
     * 我的城市code
     * @param $params
     * @return mixed
     */
    public static function myCityCodes($params) {
        $admin = new Admin();
        $role_id = $admin->where('id', $params['user_id'])->value('role_id');
        $adminRole = new AdminRole();
        //角色对应的城市code
        $city_codes = $adminRole->where('id', $role_id)->value('city_codes');
        return $city_codes;
    }
}
